package com.inspur.dgov.vlbod.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.inspur.dgov.vlbod.constant.ServiceConstant;
import com.inspur.dgov.vlbod.constant.UpAndCollectConstant;
import com.inspur.dgov.vlbod.entity.DemandBroadcast;
import com.inspur.dgov.vlbod.entity.DemandVideoUrl;
import com.inspur.dgov.vlbod.helper.XyVideoHelper;
import com.inspur.dgov.vlbod.mapper.DemandBroadcastMapper;
import com.inspur.dgov.vlbod.service.DemandBroadcastService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inspur.dgov.vlbod.vo.DemandBroadcastVO;
import com.inspur.dgov.vlbod.vo.LiveBroadcastVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chiyupei
 * @since 2023-05-28
 */
@Service
public class DemandBroadcastServiceImpl extends ServiceImpl<DemandBroadcastMapper, DemandBroadcast> implements DemandBroadcastService {

    @Resource
    private DemandBroadcastMapper demandBroadcastMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private XyVideoHelper xyVideoHelper;

    /**
     * 获取点播列表
     *
     * @param page
     * @param data
     * @return
     */
    @Override
    public Page<DemandBroadcastVO> queryList(Page<DemandBroadcastVO> page, JSONObject data) {
        // 使用 demandBroadcastMapper 对应的查询方法查询满足条件 data 的数据列表，分页信息在 page 中指定
        Page<DemandBroadcastVO> demandBroadcastVOPage = this.demandBroadcastMapper.queryList(page, data);
        // 从查询结果中获取记录列表
        List<DemandBroadcastVO> records = demandBroadcastVOPage.getRecords();
        // 遍历记录列表，逐一处理每条记录的点赞和收藏数量
        for (int i = 0; i < records.size(); i++) {
            // 获取当前查询结果对象
            DemandBroadcastVO record = records.get(i);
            // 获取当前记录的唯一标识符
            String reidsId = record.getId();

            // 构造 Redis 中点赞和收藏相关的键名
            String redisCollectId = UpAndCollectConstant.DEMAND_COLLECT_ZSET + reidsId;
            String redisUpId = UpAndCollectConstant.DEMAND_THUMBSUP_ZSET + reidsId;
            // 查询 Redis 中该记录的点赞数和收藏数，并将结果设置到查询结果中
            Long upCount = redisTemplate.opsForZSet().size(redisUpId);
            Long collectCount = redisTemplate.opsForZSet().size(redisCollectId);
            record.setThumbsUpNum(Math.toIntExact(null == upCount ? 0 : upCount));
            record.setCollectNum(Math.toIntExact(null == collectCount ? 0 : collectCount));
        }
        return demandBroadcastVOPage;
    }

    /**
     * 获取我的收藏点播列表
     *
     * @param page
     * @param data
     * @return
     */
    @Override
    public Page<DemandBroadcastVO> queryCollectList(Page<DemandBroadcastVO> page, JSONObject data) {
        Page<DemandBroadcastVO> demandBroadcastVOPage = this.demandBroadcastMapper.queryCollectList(page, data);
        List<DemandBroadcastVO> records = demandBroadcastVOPage.getRecords();
        for (int i = 0; i < records.size(); i++) {
            // 获取当前查询结果对象
            DemandBroadcastVO record = records.get(i);
            // 获取当前记录的唯一标识符
            String reidsId = record.getId();

            // 构造 Redis 中点赞和收藏相关的键名
            String redisCollectId = UpAndCollectConstant.DEMAND_COLLECT_ZSET + reidsId;
            String redisUpId = UpAndCollectConstant.DEMAND_THUMBSUP_ZSET + reidsId;
            // 查询 Redis 中该记录的点赞数和收藏数，并将结果设置到查询结果中
            Long upCount = redisTemplate.opsForZSet().size(redisUpId);
            Long collectCount = redisTemplate.opsForZSet().size(redisCollectId);
            record.setThumbsUpNum(Math.toIntExact(null == upCount ? 0 : upCount));
            record.setCollectNum(Math.toIntExact(null == collectCount ? 0 : collectCount));
        }
        return demandBroadcastVOPage;
    }

    @Override
    public List<DemandVideoUrl> getDemandBroadcastVideoUrl(String id) {
        DemandBroadcast demandBroadcast = this.getById(id);
        if (demandBroadcast == null) {
            return null;
        }
        List<Map> liveMaps = xyVideoHelper.selectLiveVideoList(demandBroadcast.getLiveId(),
                demandBroadcast.getMeetingRoomNumber());
        if (liveMaps == null || liveMaps.isEmpty()) {
            return null;
        }
        List<DemandVideoUrl> demandVideoUrls = new ArrayList<>();
        Map<String, Object> liveMap = liveMaps.get(0);
        List<Map<String, Object>> urlMaps = (List<Map<String, Object>>) liveMap.get("videos");
        for (Map<String, Object> urlMap : urlMaps) {
            String url = (String) urlMap.get("url");
            Long startTimestamp = MapUtil.getLong(urlMap, "startTimestamp");
            Long endTimestamp = MapUtil.getLong(urlMap, "endTimestamp");
            Long durationMs = MapUtil.getLong(urlMap, "durationMs");
            DemandVideoUrl demandVideoUrl = new DemandVideoUrl();
            demandVideoUrl.setUrl(url);
            DateTime startDate = DateUtil.date(startTimestamp);
            DateTime endDate = DateUtil.date(endTimestamp);
            demandVideoUrl.setStartTime(DateUtil.format(startDate, "yyyy-MM-dd HH:mm:ss"));
            demandVideoUrl.setEndTime(DateUtil.format(endDate, "yyyy-MM-dd HH:mm:ss"));
            demandVideoUrl.setDuration(DateUtil.secondToTime((int) (durationMs / 1000)));
            demandVideoUrls.add(demandVideoUrl);
        }
        return demandVideoUrls;
    }

}
